import React, { useState } from 'react'
import Taro from '@tarojs/taro'
import styles from './index.module.less'
import { Button, View, RadioGroup, Label, Radio } from '@tarojs/components'
import { AtTextarea, AtImagePicker } from 'taro-ui'
import { uploadFilerequest, request } from '../../utils/request'
import { useRequest } from 'ahooks'
const initState = {
  content: "",
  picture: ''
}
const initFiles = []

const creaetFunc = (data) => {
  return request('post', '/app/goods', data)
}

const CreateUsed: React.FC<{}> = ({ }) => {
  const [data, setData] = useState({ ...initState })
  const [files, setFiles] = useState([...initFiles])
  const onChange = (e: Array<any>, operationType: string, index: number) => {
    if (operationType === 'add') {
      uploadFilerequest('/app/goods/images', e[files.length].url, 'file').then((res) => {
        // @ts-ignore
        setData({ picture: res, content: data.content })
        // @ts-ignore
        setFiles([...files, { url: e[files.length].url }])
      })
    } else {
      // @ts-ignore
      setFiles(e)
      setData({
        content: data.content,
        picture: ''
      })
    }
  }
  const types = [
    { value: "0", text: '商品' },
    { value: "1", text: '求购' },
    { value: "2", text: '招领' },
  ]
  const [type, setType] = useState(-1)
  const creaet = useRequest(creaetFunc, {
    manual: true,
    onSuccess: d => {
      if (d) return
      Taro.showToast({
        title: '发布成功',
        icon: 'none'
      })
      setData(initState)
      setFiles(initFiles)
      setType(-1)
    }
  })

  const save = () => {
    if (type === -1) {
      Taro.showToast({
        title: '请选择类型',
        icon: 'none'
      })
      return
    }
    creaet.run({ ...data, type })
  }
  return (
    <View className={styles.create}>
      <AtTextarea value={data.content}
        height={400}
        onChange={(e) => { setData({ content: e, picture: data.picture }) }}
        maxLength={400}
        placeholder='你的问题是...' />
      <View className={styles.RadioGroup}>
        <RadioGroup
          onChange={(e) => setType(Number(e.detail.value))}
        >
          {types.map((item, i) => {
            return (
              <Label className='radio-list__label' key={i}>
                <Radio className='radio-list__radio' value={item.value} checked={type === Number(item.value)}>{item.text}</Radio>
              </Label>
            )
          })}
        </RadioGroup></View>
      <AtImagePicker
        multiple={false}
        showAddBtn={data.picture === ''}
        files={files}
        count={1}
        onChange={onChange} />
      <Button type='primary' loading={false} onClick={save}>保 存</Button>
    </View>
  )
}

export default CreateUsed